<template>
    <div class="newWindow">
      <baidu-map class="bm-view" :center="center" :zoom="zoom"  @ready="initMap" scroll-wheel-zoom :ak="AK">
        <div class="search">
          <bm-auto-complete v-model="centerValue" :sugStyle="{ zIndex: 999999 }">
            <el-input placeholder="搜电站标签号Sn" v-model.trim="centerValue" class="input-with-select" style="width: 600px">
              <!-- <el-button @click="searchAdd" slot="append" icon="Search" style="border-right: 1px solid #eeeeee; color: #fff">名称搜索</el-button> -->
              <!-- <el-button @click="getBaiduMapPoint" slot="append" icon="Search" style="border-right: 1px solid #eeeeee; color: #fff">所在地搜索</el-button> -->
              <template #append>
                <el-button :icon="Search"  @click="searchAdd">标签号搜索</el-button>
              </template>
            </el-input>
          </bm-auto-complete>
        </div>
        <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
      </baidu-map>
    </div>
  </template>

  <script setup lang="ts" name="Map">
      import { Search } from "@element-plus/icons-vue"
      import { BmMarker, BmView, BmGeolocation,useGeocoder, usePoint } from 'vue-baidu-map-3x';
      import { getAllStation } from '@/api/homeIndex';
      import { useSettingsStore } from '@/store/modules/settings';
      import { useStationStore } from '@/store/modules/station';
      import { useI18n } from 'vue-i18n'
      const { t } = useI18n()
      // import BMapGL from 'baidu-map';
      import util from '@/utils/util';
      const settingStore = useSettingsStore();
      const router = useRouter();
      const props = defineProps({
        // 缩放等级
        zoom: {
          type: [String, Number],
          default: 12
        },
        // 中心点
        center: {
          type: [Object],
          default: { lng: 116.403981, lat: 39.917702 }
        },
      });

      const AK = ref('hZcI1sg4du1R9keupBDb0npiGgxv5e2G');// 密钥
      let Map = {};
      let bMap = null;
      const position = ref([]); // 点位集合
      const visible = ref(false); // 弹框控制
      const POIList = ref([]);
      const dianzhanList = ref([]);
      const centerValue = ref('');

      onMounted(()=> {
        getStation();
        // 存到本地存储 header电站名和导航 显示与隐藏
        settingStore.setHeaderSum(5);
      });

      // 获取经纬度
      const getStation= async() => {
        let query = {
          searchValue: centerValue.value,
        };
        let res = await getAllStation(query);
        dianzhanList.value = res.data;
      };

      const searchAdd = async ()=>  {
        let query = {
          searchValue: centerValue.value,
        };
        let res = await getAllStation(query);
        if (res.data && res.data.length > 0) {
          // 地图中心店移到指定位置
          var point = new bMap.Point(res.data[0].gpsLngValue, res.data[0].gpsLatValue);
          Map.centerAndZoom(point, 18);
          Map.panTo(point)
        } else {
          ElMessage.error(t('licence.none'));
        }
      };
      const getBaiduMapPoint = async ()=>  {
        let myGeo = new bMap.Geocoder();
        //逆地址解析
        myGeo.getPoint(centerValue.value, function (point) {
          if (point) {
            Map.centerAndZoom(point, 15);
          }
        });
      };

      /**
       * 初始化地图
       * BMap 地图容器
       * Map 地图实例
       */
      const initMap = ({ BMap, map }) => {
      	console.log('map:', map)
      	console.log('BMap:', BMap)
        bMap = BMap;
        Map=map
        // 添加marker
        addPointer(bMap, Map);
        getLocation(function (e) {
          getLocationAddress(e.point.lng, e.point.lat, function (result) {
            result.address;
          });
        });
      };

      /**
       * 逆地址解析
       * lng 经度
       * lat 纬度
       */
      const getLocationAddress = (lng:any, lat:any, cb:any) => {
        let myGeo = new bMap.Geocoder();
        // 根据坐标得到地址描述
        myGeo.getLocation(new bMap.Point(lng, lat), function (result:any) {
          if (result) {
            console.log(' 地址解析', result);
            POIList.value = result.surroundingPois;
            cb && cb(result);
          }
        });
      };
      /**
       * 添加点
       * @param BMap
       * @param map
       * @param lng 经度
       * @param lat 纬度
       * @param icon 图标
       * @param offX x偏移
       * @param offY y偏移
       */
      const addPointer = (BMap:any, map:any, { icon = 'mapadd.png', offX = 35, offY = 20 } = {}) => {
        // 清除marker
        Map.clearOverlays();
        for (let i = 0; i <= dianzhanList.value.length - 1; i++) {
          // 创建点位
          let point = new bMap.Point(dianzhanList.value[i].gpsLngValue, dianzhanList.value[i].gpsLatValue);
          // 创建标注
          let marker = new bMap.Marker(point);

          // 创建icon
          let iconPath = util.getAssetsFile(icon);
          // let iconPath = require('../../assets/images/' + icon);

          let myIcon = new bMap.Icon(iconPath, new bMap.Size(100, 100), {
            imageOffset: new bMap.Size(offX, offY), // 设置图片偏移
          });
          // 设置icon
          marker.setIcon(myIcon);
          // 添加点位
          Map.addOverlay(marker);
          if (localStorage.getItem('locale') == 'en_US') {
            var html = '<span>location：</span>' + dianzhanList.value[i].address + '<br>' + '<span>capacity(KW)：</span>' + dianzhanList.value[i].installedCapacity + '<br>' + "<input type='button' id='btn' style='color:#fff; width:90px; height:30px ;background:#305add;border:none;border-radius: 4px; cursor: pointer;' value='detail'>";
          } else {
            var html = '<span>电站地址：</span>' + dianzhanList.value[i].address + '<br>' + '<span>装机功率(KW)：</span>' + dianzhanList.value[i].installedCapacity + '<br>' + "<input type='button' id='btn' style='color:#fff; width:90px; height:30px ;background:#305add;border:none;border-radius: 4px; cursor: pointer;' value='查看详情'>";
          }
          let opts = {
            width: 400, // 信息窗口宽度
            height: 120, // 信息窗口高度
            title: dianzhanList.value[i].stationName,
          };
          let infoWindow = new bMap.InfoWindow(html, opts); // 创建信息窗口对象
          marker.addEventListener('click', function () {
            Map.openInfoWindow(infoWindow, point); //开启信息窗口
          });
          if (!infoWindow.isOpen()) {
            infoWindow.addEventListener('open', function (e) {
              document.getElementById('btn').onclick = function () {
                // 存到本地存储
                useStationStore().setPowerInfo(dianzhanList.value[i])
                router.push('/dianzhan');
              };
            });
          } else {
            var btn = document.getElementById('btn');
            btn.onclick = function () {
              // 存到本地存储
              useStationStore().setPowerInfo(dianzhanList.value[i])
              router.push('/dianzhan');
            };
          }
        }
      };
      /**
       * 添加标注
       * @param BMap
       * @param map
       * @param text label内容
       * @param lng 经度
       * @param lat 纬度
       * @param icon 图标
       * @param offX x偏移
       * @param offY y偏移
       */

      // 定位当前位置
      const getLocation = async(cb) => {
        let geolocation = new bMap.Geolocation();
        console.log('geolocation:', geolocation)
        const options = {
          enableHighAccuracy: true, // 是否要求浏览器获取最佳效果
          timeout: 5000,            // 超时事件，单位为毫秒。默认为10秒
          maximumAge: 10*3000,            // 允许返回指定事件内的缓存结果，单位为毫秒。如果为0，则每次请求都获取最新的定位结果。默认为10分钟
        };
        geolocation.getCurrentPosition(function (r) {
          if (r?.point) {
            let { lng, lat } = r.point;
            // 修改中心点
            Map.panTo(r.point);
            // 添加marker
            addPointer(bMap, Map);
            cb && cb(r);
          } else {
            alert('failed: 定位失败');
          }
        },options);
      };
  </script>

  <style scoped lang="scss">
  .newWindow {
    height: 100% !important;
  }
  .bm-view {
    // border: 2px solid green;
    width: 100%;
    margin: auto;
    height: 95vh;
  }
  .search {
    position: absolute;
    top: 60px;
    z-index: 1;
    left: 60px;
  }
  ::v-deep .el-input-group__append {
    background-color: #305add;
    border: 1px solid #305add;
  }
  ::v-deep .el-icon-search:before {
    color: #fff;
  }
  ::v-deep .el-input__inner {
    // border: 1px solid #305add;
  }
  // ::v-deep .BMap_bubble_content input{
  //   background: #f3f2f2 !important;
  // }
  </style>
